package mytomcat.servlet;

import mytomcat.core.MyRequest;
import mytomcat.core.MyResponse;
import mytomcat.servlet.base.MyServlet;

import java.io.*;

/**
 * <ul>
 * <li>Title:  HelloWorldServlet</li>
 * <li>Description: TODO </li>
 * <li>Copyright: Copyright (c) 2018</li>
 *
 * </ul>
 *
 * @author swc
 * @version     V1.0
 * @date 2020/4/20 0020 上午 9:53
 */
public class IndexServlet extends MyServlet {


    @Override
    public void doGet(MyRequest myRequest, MyResponse myResponse) {
        doHand(myRequest,myResponse);
    }



    public void doPost(MyRequest myRequest, MyResponse myResponse) {
        doHand(myRequest,myResponse);
    }


    private void doHand(MyRequest myRequest,MyResponse myResponse) {
        String viewRoot ="src\\webapp\\view\\";
        try {
            String root =System.getProperty("user.dir");
            viewRoot = root.split("src\\\\main\\\\java")[0]+viewRoot;

            FileInputStream fileInputStream = new FileInputStream(viewRoot+"index.html");
            StringBuffer sbf = new StringBuffer();
            byte[] buf = new byte[1024];
            int length = 0;
            while((length = fileInputStream.read(buf)) != -1){
                sbf.append(new String(buf,0,length));
            }
            //最后记得，关闭流
            fileInputStream.close();
            myResponse.write(sbf.toString().replace("${ctx}","http://localhost:"+myRequest.getPort()));
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }
}
